package cn.jee.jsp.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
@WebFilter("/*")
public class LogFilter extends HttpFilter {
  @Override
  protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
    System.out.println("====>"+req.getRequestURI());
    System.out.println(req.getRemoteAddr());
    Map<String,String[]> paraMaps=req.getParameterMap();
    paraMaps.forEach((k,v)->{
      System.out.println(k+"="+ Arrays.toString(v));
    });
    chain.doFilter(req,res);
    System.out.println("===session===");
    HttpSession session=req.getSession();
    Enumeration<String> keys=session.getAttributeNames();
    while(keys.hasMoreElements()){
      String key=keys.nextElement();
      System.out.println(key+"="+session.getAttribute(key));
    }
    System.out.println("<=====");
    //response已经返回
    String contentType=res.getContentType();
    if(contentType!=null&&contentType.startsWith("text")){
      PrintWriter out=res.getWriter();
      out.print("<br><h1>JSP2025</h1>");
    }
  }
}
